package com.centerm.demo;

import android.Manifest;
import android.bluetooth.BluetoothDevice;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.centerm.bluetooth.dy.SwiperController;
import com.centerm.bluetooth.dy.listener.SwiperListener;
import com.centerm.bluetooth.dy.model.Device;
import com.centerm.bluetooth.dy.model.TransType;
import com.centerm.demo.dy.R;
import com.centerm.util.Logger;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private SwiperController swiperController;
    private TextView txtvw;
    private BluetoothDialog bluetoothDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtvw = (TextView) findViewById(R.id.txtvw);
        swiperController = SwiperController.getControllerInstance(this);
        Logger.setDEBUG(true,true);
        swiperController.setSwiperListener(new SwiperCallback());
        bluetoothDialog = new BluetoothDialog(this);

        if (Build.VERSION.SDK_INT >= 23) {
            int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            Logger.i(" permission == " + permission + " == " + PackageManager.PERMISSION_GRANTED);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                Logger.i(" requestPermissions ");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void onSeach(View v) {
        bluetoothDialog.show();
        swiperController.startScanDevice(10);
    }

    public void onConnect(View v) {
        BluetoothDevice device = bluetoothDialog.getSel();
        if (device != null)
            swiperController.conectDevice(device);
    }

    public void onVersionClick(View v) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Device device = swiperController.getDeviceInfo();
                if (device != null) {
                    Logger.i(device);
                    logsBuffer.append(" == onBackCardNo == ").append(JSON.toJSONString(device)).append("\n");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            txtvw.setText(logsBuffer);
                        }
                    });
                }
            }
        }).start();

    }

    public void onResetClick(View v) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                swiperController.cancelWaitForCard();
            }
        }).start();

    }

    public void openCardReader(View v) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean res = swiperController.startPOS("000000000001", "000001", 0.01, TransType.TransType_Payment, 10);
                logsBuffer.append("开卡结果：").append(res).append("\n");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        txtvw.setText(logsBuffer.toString());
                    }
                });
            }
        }).start();

    }

    public void openCardReaderQuery(View v) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean res =                 swiperController.startPOS("000000000001", "000001", 0.01, TransType.TransType_Inquiry, 60);
                logsBuffer.append("开卡结果：").append(res).append("\n");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        txtvw.setText(logsBuffer.toString());
                    }
                });
            }
        }).start();

    }

    public void onScreenClick(View v) {
        swiperController.LcdString(4, 0, "中文显示");
    }

    public void releaseDevice(View v) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                swiperController.releaseDevice();
                logsBuffer.append("释放SDK资源").append("\n");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        txtvw.setText(logsBuffer.toString());
                    }
                });
            }
        }).start();

    }

    public void startGetCardNo(View v) {
        swiperController.startGetCardNo();
    }

    public void clearLog(View v) {
        logsBuffer.delete(0, logsBuffer.length() - 1);
        txtvw.setText(logsBuffer.toString());
    }

    private StringBuffer logsBuffer = new StringBuffer();

    private class SwiperCallback implements SwiperListener {

        @Override
        public void onDeviceConnected() {
            logsBuffer.append(" == onDeviceConnected == \n");
            txtvw.setText(logsBuffer);
        }

        @Override
        public void onDeviceDisConnected() {
            logsBuffer.append(" == onDeviceDisConnected == \n");
            txtvw.setText(logsBuffer);
        }

        @Override
        public void onDeviceScanTimeout() {
            logsBuffer.append(" == onDeviceScanTimeout == \n");
            txtvw.setText(logsBuffer);
        }

        @Override
        public void onDeviceConnectTimeout() {
            logsBuffer.append(" == onDeviceConnectTimeout == \n");
            txtvw.setText(logsBuffer);
        }

        @Override
        public void onFindDevices(List<BluetoothDevice> devices) {
            logsBuffer.append(" == onFindDevices == ").append(JSON.toJSONString(devices)).append("\n");
            txtvw.setText(logsBuffer);
            bluetoothDialog.addAll(devices);
        }

        @Override
        public void onYJEMVError(int errorCode, String errorMessage) {
            logsBuffer.append(" == onYJEMVError == errorCode = ").append(errorCode).append(" = errorMessage = ")
                    .append(errorMessage).append("\n");
            txtvw.setText(logsBuffer);
        }

        @Override
        public void onGetTrackData(String txtPan, String data) {
            logsBuffer.append(" == onGetTrackData == txtPan = ").append(txtPan).append(" = ").append(data).append("\n");
            txtvw.setText(logsBuffer);
        }

        @Override
        public void onSwipeCardCancel() {
            logsBuffer.append(" == onSwipeCardCancel == ").append("\n");
            txtvw.setText(logsBuffer);
        }

        @Override
        public void onBackCardNo(String cardNo) {
            logsBuffer.append(" == onBackCardNo == ").append(cardNo).append("\n");
            txtvw.setText(logsBuffer);
        }
    }

}
